package com.t168.appinfo.controller.reception;

import java.io.File;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.t168.appinfo.entity.AppInfo;
import com.t168.appinfo.entity.AppVersion;
import com.t168.appinfo.entity.DevUser;
import com.t168.appinfo.service.reception.appinfo.AppInfoService;
import com.t168.appinfo.service.reception.appversion.AppVersionService;

@Controller
@RequestMapping("/appVersion")
public class AppVersionController {

	private Logger logger = Logger.getLogger(AppVersionController.class);
	
	@Resource(name="appVersionService")
	private AppVersionService appVersionService;

	public AppVersionService getAppVersionService() {
		return appVersionService;
	}

	public void setAppVersionService(AppVersionService appVersionService) {
		this.appVersionService = appVersionService;
	}
	
	@Resource(name="appInfoService")
	private AppInfoService appInfoService;
	
	public AppInfoService getAppInfoService() {
		return appInfoService;
	}

	public void setAppInfoService(AppInfoService appInfoService) {
		this.appInfoService = appInfoService;
	}

	@RequestMapping(value="/appversionadd.html")
	public String appVersionAdd(@RequestParam(value = "id")String id,HttpServletRequest request){
		AppInfo appVersion = appInfoService.historyVersion(Integer.valueOf(id).intValue());
		request.setAttribute("appVersion", appVersion);
//		AppVersion version = 
		
		return "jsp/developer/appversionadd";
	}
	
	@RequestMapping(value="/addversionsave")
	public String addAppVersionSave(@ModelAttribute("appVersion")AppVersion appVersion,@RequestParam(value ="a_downloadLink", required = false) MultipartFile attach,HttpSession session,HttpServletRequest request){
		
		String downloadLink = null;
		String apkLocPath = null;
		//判断文件是否为空
		if(!attach.isEmpty()){
			//定义上传的目标路径
			//String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles"); 
			String path = "E:\\workspace\\AppInfoSystem\\WebContent\\statics\\uploadfiles";
			logger.info("uploadFile path ============== > "+path);
			//获取原文件名
			String oldFileName = attach.getOriginalFilename();
			logger.info("uploadFile oldFileName ============== > "+oldFileName);
			//获取原文件名的后缀
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀     
	        logger.debug("uploadFile prefix============> " + prefix);
			if(prefix.equalsIgnoreCase("apk")){//上传图片格式不正确
            	//新的照片名称，毫秒数加随机数，确保不能重复
            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.apk";  
                logger.debug("new fileName======== " + attach.getName());
                //创建文件对象，此文件对象用于接收用户上传的文件流
                File targetFile = new File(path, fileName);  
                if(!targetFile.exists()){  
                    targetFile.mkdirs();  
                }  
                //保存  
                try {  
                	//把MultipartFile中的文件流数据的数据输出至目标文件中
                	attach.transferTo(targetFile);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                    request.setAttribute("uploadFileError", " * 上传失败！");
                	return "forward:/appVersion/appversionadd.html?id="+appVersion.getAppId();
                }
                downloadLink = "statics/uploadfiles/"+fileName;
                
                //获取文件的的名称保存到数据库中
                apkLocPath = path+File.separator+fileName;
            }else{
            	request.setAttribute("uploadFileError", " * 请上传apk文件");
            	return "forward:/appVersion/appversionadd.html?id="+appVersion.getAppId();
            }
		}
		
		
		
		boolean flag = true;
		appVersion.setDownloadLink(downloadLink);
		String apkFileName = appVersion.getApkFileName()+"-"+appVersion.getVersionNo()+".apk";
		appVersion.setApkFileName(apkFileName);
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setCreatedBy(((DevUser) session.getAttribute("devUser")).getId());
		appVersion.setCreationDate(new Date());
		if(appVersionService.addAppVersionSave(appVersion)){
			flag = false;
		}else{
			flag = true;
		}
		System.out.println(appVersion.getAppId());
		int id = appVersionService.getNewVersionId(appVersion.getAppId());
		
		if(appInfoService.modifyAppVersionId(appVersion.getAppId(), id)){
			flag = false;
		}else{
			flag = true;
		}
		
		
		if(!flag){
			return "redirect:/appInfo/appInfolist.html";
		}else{
			request.setAttribute("uploadFileError", "添加失败");
			return "forward:/appVersion/appversionadd.html?id="+appVersion.getAppId();
		}
		
	}
	
	
	@RequestMapping("/appversionmodify")
	public String modifyVersionView(@RequestParam("appId")int appId,HttpServletRequest request){
		AppVersion appVersion = appVersionService.getVersionInfoByAId(Integer.valueOf(appId).intValue());
		AppInfo appInfoVersion = appInfoService.historyVersion(Integer.valueOf(appId).intValue());
		request.setAttribute("appVersion", appVersion);
		request.setAttribute("appInfoVersion", appInfoVersion);
		System.out.println(appVersion.getVersionNo());
		return "jsp/developer/appversionmodify";
	}
	
	@RequestMapping("/appversionmodifysave")
	public String appversionmodifysave(@ModelAttribute("appVersion") AppVersion appVersion,@RequestParam(value ="attach", required = false) MultipartFile attach,HttpSession session,HttpServletRequest request){
		String downloadLink = null;
		String apkLocPath = null;
		//判断文件是否为空
		if(!attach.isEmpty()){
			//定义上传的目标路径
			//String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles"); 
			String path = "E:\\workspace\\AppInfoSystem\\WebContent\\statics\\uploadfiles";
			logger.info("uploadFile path ============== > "+path);
			//获取原文件名
			String oldFileName = attach.getOriginalFilename();
			logger.info("uploadFile oldFileName ============== > "+oldFileName);
			//获取原文件名的后缀
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀     
	        logger.debug("uploadFile prefix============> " + prefix);
			if(prefix.equalsIgnoreCase("apk")){//上传图片格式不正确
            	//新的照片名称，毫秒数加随机数，确保不能重复
            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.apk";  
                logger.debug("new fileName======== " + attach.getName());
                //创建文件对象，此文件对象用于接收用户上传的文件流
                File targetFile = new File(path, fileName);  
                if(!targetFile.exists()){  
                    targetFile.mkdirs();  
                }  
                //保存  
                try {  
                	//把MultipartFile中的文件流数据的数据输出至目标文件中
                	attach.transferTo(targetFile);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "redirect:/appVersion/appversionmodify?appId="+appVersion.getAppId();
                }
                downloadLink = "statics/uploadfiles/"+fileName;
                
                //获取文件的的名称保存到数据库中
                apkLocPath = path+File.separator+fileName;
                
                appVersion.setDownloadLink(downloadLink);
                appVersion.setApkLocPath(apkLocPath);
            }else{
            	request.setAttribute("uploadFileError", " * 请上传apk文件");
            	return "redirect:/appVersion/appversionmodify?appId="+appVersion.getAppId();
            }
		}
		
		
		appVersion.setModifyBy(((DevUser)session.getAttribute("devUser")).getId());
		appVersion.setModifyDate(new Date());
		
		if(appVersionService.modifyVersionInfo(appVersion)){
			return "redirect:/appInfo/appInfolist.html";
		}else{
			request.setAttribute("uploadFileError", "修改失败！");
			return "redirect:/appVersion/appversionmodify?appId="+appVersion.getAppId();
		}
		
	}
	
	
	
}
